import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import { storage } from '@/utils/storage'

export interface ThemeConfig {
  primaryColor: string
  mode: 'light' | 'dark'
}

export const useThemeStore = defineStore('theme', () => {
  const config = ref<ThemeConfig>({
    primaryColor: '#409EFF',
    mode: 'light'
  })

  // 从本地存储恢复主题配置
  const savedConfig = storage.get('theme')
  if (savedConfig) {
    config.value = savedConfig
  }

  // 监听配置变化并保存
  watch(config, (newConfig) => {
    storage.set('theme', newConfig)
    applyTheme(newConfig)
  }, { deep: true })

  // 应用主题
  function applyTheme(theme: ThemeConfig) {
    const style = document.documentElement.style
    style.setProperty('--el-color-primary', theme.primaryColor)
    
    if (theme.mode === 'dark') {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }

  // 初始应用主题
  applyTheme(config.value)

  return {
    config
  }
}) 